import { PrismaService } from '@app/prisma';
import { Body, Controller, ForbiddenException, Get, Post, Query, UseGuards } from '@nestjs/common';
import { TaskService } from './task.service';
import { CurrentUser, JwtAuthGuard } from 'src/auth/auth.guard';
import { UserEntity } from '@app/prisma/user.entity/user.entity';

@Controller('task')
export class TaskController {
    constructor(
        private readonly prisma: PrismaService,
        private readonly taskService: TaskService
    ) { }


    @Get("getSelfTask")
    @UseGuards(JwtAuthGuard)
    async getSelfTask(
        @CurrentUser() user: UserEntity
    ) {
        if (!user.classesId) return {}
        const tasks = await this.prisma.task.findMany({
            where: {
                TaskOnClasses: {
                    some: {
                        classesId: user.classesId
                    }
                },
                status: true
            },
            include: {
                _count: {
                    select: {
                        UserOnTask: {
                            where: {
                                userId: user.id
                            }
                        }
                    }
                }
            },
            orderBy: {
                id: "desc"
            }
        });
        const classes = await this.prisma.classes.findUnique({
            where: {
                id: user.classesId
            },
            include: {
                _count: {
                    select: {
                        TeacherOnClasses: true
                    }
                }
            }
        })
        return {
            tasks,
            teacherCount: classes._count.TeacherOnClasses
        }
    }

    @Post("getTaskItemInfo")
    @UseGuards(JwtAuthGuard)
    async getTaskItemInfo(
        @Body() { id, teacherId }
    ) {
        id = Number(id)
        teacherId = Number(teacherId)
        const task = await this.prisma.task.findUnique({
            where: {
                id,
                status: true,
            },
            include: {
                TaskItem: true
            }
        })
        const teacher = await this.prisma.teacher.findUnique({
            where: {
                id: teacherId
            }
        })
        return {
            items: task.TaskItem,
            teacher
        }
    }

    @Post("send")
    @UseGuards(JwtAuthGuard)
    async send(
        @Body() {
            form,
            common,
            id,
            teacherId
        },
        @CurrentUser() user: UserEntity
    ) {
        id = Number(id)
        teacherId = Number(teacherId)
        const task = await this.prisma.task.findUnique({
            where: {
                id
            },
            include: {
                TaskItem: true
            }
        })
        if (Object.keys(form).length !== task.TaskItem.length)
            throw new ForbiddenException("提交数据样本异常，请重试")
        await this.prisma.userOnTask.create({
            data: {
                user: {
                    connect: {
                        id: user.id
                    }
                },
                teacher: {
                    connect: {
                        id: teacherId
                    }
                },
                common,
                task: {
                    connect: {
                        id
                    }
                }
            }
        })
        await this.prisma.userTaskItem.createMany({
            data: task.TaskItem.map(({ id }) => {
                return {
                    taskItemId: id,
                    userOnTaskUserId: user.id,
                    userOnTaskTaskId: task.id,
                    userOnTaskTeacherId: teacherId,
                    score: form[id]
                }
            })
        })
        for (const item of task.TaskItem) {
            await this.prisma.taskOnTeacherItem.update({
                where: {
                    taskItemId_teacherId: {
                        teacherId,
                        taskItemId: item.id
                    }
                },
                data: { 
                    score: {
                        increment: form[item.id],
                    },
                    count: {
                        increment: 1
                    }
                }
            })
        }
    }


    @Post("getTaskDetail")
    @UseGuards(JwtAuthGuard)
    getTaskDetail(
        @Body() { id },
        @CurrentUser() user: UserEntity
    ) {
        if (!user.classesId || !id) return null;

        return this.prisma.task.findUniqueOrThrow({
            where: {
                id: parseInt(id)
            },
            include: {
                TaskItem: true,
                TaskOnClasses: {
                    where: {
                        classes: {
                            User: {
                                some: {
                                    id: user.id
                                }
                            }
                        }
                    },
                    include: {
                        classes: {
                            include: {
                                TeacherOnClasses: {
                                    include: {
                                        teacher: true
                                    }
                                }
                            }
                        }
                    }
                },
                UserOnTask: {
                    where: {
                        userId: user.id
                    },
                    include: {
                        teacher: true
                    }
                }
            }
        })
    }


}
